package org.sxf.app.sign.handler;

import java.lang.Thread.UncaughtExceptionHandler;
import android.content.Context;
import com.lidroid.xutils.util.LogUtils;

import org.sxf.app.sign.constants.Constants;
import org.sxf.app.sign.utils.ConfigFileUtilsSingleton;
import org.sxf.app.sign.utils.Utility;

// 程序崩溃异常捕获类
public class CrashHandlerSingleton implements UncaughtExceptionHandler{

	private static CrashHandlerSingleton singleton = new CrashHandlerSingleton(); 
	public static final String TAG = CrashHandlerSingleton.class.getCanonicalName();  
//	XqApp _application;
	
	//程序的Context对象  
    private Context mContext; 
  //系统默认的UncaughtException处理类   
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    
	public static CrashHandlerSingleton getInstance(){
		return singleton;
	}
	
	public CrashHandlerSingleton() {

	}

	public void init(Context context/** , XqApp application */) {
		mContext = context;
		// 获取系统默认的UncaughtException处理器
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		// 设置该CrashHandler为程序的默认处理器
		Thread.setDefaultUncaughtExceptionHandler(this);
//		this._application = application;
	}
	 

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {

		if (Constants.UPLOAD_CRASH_REPORT){
			if (!handleException(ex) && mDefaultHandler != null) {
				// 如果用户没有处理则让系统默认的异常处理器来处理
				APPHandler.getInstance().clearAllActivity();
				mDefaultHandler.uncaughtException(thread, ex);
			} else {
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					//  e.printStackTrace();
				}
//				_application.restartAPP();
				APPHandler.getInstance().exit();
			}
		}else {
			APPHandler.getInstance().clearAllActivity();
			mDefaultHandler.uncaughtException(thread, ex);
		}

	}

	
	  /** 
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 
     *  
     * @param ex 
     * @return true:如果处理了该异常信息;否则返回false. 
     */  
    private boolean handleException(Throwable ex) {  

		// 可将exception上传到服务器
		ConfigFileUtilsSingleton.getInstance().writeConfig(Constants.CONFIG_KEY_CRASH_INFO, Utility.getCutStackTrace(ex));
        LogUtils.e(Utility.getCutStackTrace(ex));
        
        return true;  
    }


}
